package wh2_aaronchen;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.FileNameMap;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Date;

public class WebGISHttpServer {

	public static final String pagePosition = "webservice";

	public static void main(String[] args) throws IOException {
		@SuppressWarnings("resource")
		ServerSocket server = new ServerSocket(80);
		while (true) {
			Socket socket = server.accept();
			new HttpSocketHandler(socket);
		}
	}

}

class HttpSocketHandler implements Runnable {
	private Socket socket;

	HttpSocketHandler(Socket s) {
		this.socket = s;
		new Thread(this).start();
	}

	@Override
	public void run() {
		FileInputStream fis = null;
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			OutputStream os = socket.getOutputStream();
			String firstLine = br.readLine();
			String[] request = firstLine.split(" ");
			if (request[1].trim().equals("/")) {
				request[1] += "index.html";
			}
			File file = new File(WebGISHttpServer.pagePosition + request[1]);
			if (request[0].trim().equals("GET") && file.exists()
					&& file.length() < Integer.MAX_VALUE) {
				fis = new FileInputStream(file);
				byte[] fbytes = new byte[(int) file.length()];
				int fl = fis.read(fbytes);
				if (fl == file.length()) {
					os.write(webInfo(file));
					os.write(fbytes);
				} else {
					errorHandle();
				}
			} else {
				errorHandle();
			}
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (null != fis) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private void errorHandle() throws IOException {
		PrintWriter pw = new PrintWriter(socket.getOutputStream());
		pw.println("HTTP/1.1 404 Not Found");
	}

	@SuppressWarnings("deprecation")
	byte[] webInfo(File f) {
		String result = "HTTP/1.0 200 OK\nServer: Microsoft-IIS/5.0\n";
		result += "Date:" + new Date().toGMTString() + "\n";
		result += "Content-Type: ";
		if (f.getName().endsWith("html") || f.getName().endsWith("htm")) {
			result += "text/html;charset=" + Charset.defaultCharset().name()
					+ "\n";
		} else {
			FileNameMap fnm = URLConnection.getFileNameMap();
			result += fnm.getContentTypeFor(f.getName()) + "\n";
		}
		result += "Content-Length: " + f.length() + "\n\n";
		return result.getBytes();
	}

}
